<template>
  <div>
    <div class="flex-container" style="flex-direction: row;">
      <!-- 右侧表格 -->
      <div class="right-table-container">
        <!-- 搜索表单 -->
        <div class="search-form">
          <div class="search-form-left">
            <a-form layout="inline">
              <a-form-item label="姓名">
                <a-input v-model="searchForm.person_name" placeholder="请输入姓名" allowClear />
              </a-form-item>
              <a-form-item label="部门">
                <a-select v-model="searchForm.department_id" placeholder="请选择部门" allowClear style="width: 200px">
                  <a-select-option v-for="item in departmentList" :key="item.department_id" :value="item.department_id">
                    {{ item.department_name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item>
                <a-button type="primary" @click="handleSearch">搜索</a-button>
                <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
              </a-form-item>
            </a-form>
          </div>
          <div class="search-form-right">
            <a-button type="primary" icon="plus" @click="handleCreate">
              新增人员
            </a-button>
          </div>
        </div>

        <!-- 表格 -->
        <div class="table-container">
          <vxe-table :data="tableData" :loading="tableLoading">
            <vxe-column field="person_name" title="姓名"></vxe-column>
            <vxe-column field="position" title="职位"></vxe-column>
            <vxe-column field="phone_number" title="手机号"></vxe-column>
            <vxe-column field="department_name" title="所属部门"></vxe-column>
            <vxe-column field="role_main" title="系统管理-角色">
              <template v-slot="{ row }">
                <a-tag v-if="row.role_main === '系统管理员'" color="blue">系统管理员</a-tag>
                <a-tag v-else-if="row.role_main === '普通用户'" color="green">普通用户</a-tag>
              </template>
            </vxe-column>
            <vxe-column field="role" title="短视频管理-角色">
              <template v-slot="{ row }">
                <a-tag v-if="row.role === '系统管理员'" color="blue">系统管理员</a-tag>
                <a-tag v-else-if="row.role === '审核员'" color="orange">审核员</a-tag>
                <a-tag v-else-if="row.role === '普通用户'" color="green">普通用户</a-tag>
              </template>
            </vxe-column>
            <vxe-column field="role_destination" title="人员去向表-角色">
              <template v-slot="{ row }">
                <a-tag v-if="row.role_destination === '系统管理员'" color="blue">系统管理员</a-tag>
                <a-tag v-else-if="row.role_destination === '部门负责人'" color="orange">部门负责人</a-tag>
                <a-tag v-else-if="row.role_destination === '普通用户'" color="green">普通用户</a-tag>
              </template>
            </vxe-column>
            <vxe-column field="role_ov" title="公车管理-角色">
              <template v-slot="{ row }">
                <a-tag v-if="row.role_ov === '系统管理员'" color="blue">系统管理员</a-tag>
                <a-tag v-else-if="row.role_ov === '部门负责人'" color="orange">部门负责人</a-tag>
                <a-tag v-else-if="row.role_ov === '普通用户'" color="green">普通用户</a-tag>
              </template>
            </vxe-column>
            <vxe-column field="is_actived" title="启用状态">
              <template v-slot="{ row }">
                <!-- <a-tag v-if="row.is_actived == 1" color="#108ee9">已启用</a-tag>
                <a-tag v-else color="#f50">未启用</a-tag> -->
                <a-switch :checked="row.is_actived" @change="handleUpdateActived(row)" />
              </template>
            </vxe-column>
            <vxe-column field="password" title="密码">
              <template v-slot="{ row }">
                <a-tag v-if="row.password" color="cyan">有</a-tag>
                <a-tag v-else color="purple">无</a-tag>
              </template>
            </vxe-column>
            <vxe-column title="操作" width="200">
              <template #default="{ row }">
                <a-button class="text-btn" type="link" :loading="tableLoading" @click="handleEdit(row)">
                  编辑
                </a-button>
                <a-popconfirm title="确定要删除该人员吗？" ok-text="确定" cancel-text="取消" @confirm="handleDelete(row)">
                  <a-button style="color:red;" class="text-btn" type="link" :loading="tableLoading" danger>
                    删除
                  </a-button>
                </a-popconfirm>
                <a-popconfirm title="确定要重置密码吗？" ok-text="确定" cancel-text="取消" @confirm="handleResetPassword(row)">
                  <a-button style="color:green;" class="text-btn" type="link" :loading="tableLoading" danger>
                    重置密码
                  </a-button>
                </a-popconfirm>
              </template>
            </vxe-column>
          </vxe-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <a-pagination v-model="pagination.page" :total="pagination.total" :page-size="pagination.page_size"
              :page-size-options="['10', '20', '30', '40']" show-size-changer show-quick-jumper
              :show-total="total => `共 ${total} 条记录`" @change="handlePageChange" @showSizeChange="handleSizeChange" />
          </div>
        </div>
      </div>
    </div>

    <!-- 新增弹窗 -->
    <a-modal v-model="createVisible" title="新增人员" :confirmLoading="loading" @ok="handleOnCreate"
      @cancel="handleOnCreateCancel">
      <a-form-model ref="createForm" :model="createForm" :rules="rules" :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }">
        <a-form-model-item label="姓名" prop="person_name">
          <a-input v-model="createForm.person_name" placeholder="请输入姓名" />
        </a-form-model-item>
        <a-form-model-item label="职位" prop="position">
          <a-input v-model="createForm.position" placeholder="请输入职位" />
        </a-form-model-item>
        <a-form-model-item label="部门" prop="department_id">
          <a-select v-model="createForm.department_id" placeholder="请选择部门">
            <a-select-option v-for="item in departmentList" :key="item.department_id" :value="item.department_id">
              {{ item.department_name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="密码" prop="password">
          <a-input-password v-model="createForm.password" placeholder="请输入密码" />
        </a-form-model-item>
        <a-form-model-item label="手机号" prop="phone_number">
          <a-input v-model="createForm.phone_number" placeholder="请输入手机号" />
        </a-form-model-item>
        <a-form-model-item label="系统管理-角色" prop="role_main">
          <a-select v-model="createForm.role_main" placeholder="请选择角色">
            <a-select-option value="普通用户">普通用户</a-select-option>
            <a-select-option value="系统管理员">系统管理员</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="短视频管理-角色" prop="role">
          <a-select v-model="createForm.role" placeholder="请选择角色">
            <a-select-option value="普通用户">普通用户</a-select-option>
            <a-select-option value="审核员">审核员</a-select-option>
            <a-select-option value="系统管理员">系统管理员</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="人员去向-角色" prop="role_destination">
          <a-select v-model="createForm.role_destination" placeholder="请选择角色">
            <a-select-option value="普通用户">普通用户</a-select-option>
            <a-select-option value="部门负责人">部门负责人</a-select-option>
            <a-select-option value="系统管理员">系统管理员</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="公车管理-角色" prop="role_ov">
          <a-select v-model="createForm.role_ov" placeholder="请选择角色">
            <a-select-option value="普通用户">普通用户</a-select-option>
            <a-select-option value="部门负责人">部门负责人</a-select-option>
            <a-select-option value="系统管理员">系统管理员</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 编辑弹窗 -->
    <a-modal v-model="editVisible" title="编辑人员" :confirmLoading="loading" @ok="handleOnEdit"
      @cancel="handleOnEditCancel">
      <a-form-model ref="editForm" :model="editForm" :rules="editRules" :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }">
        <a-form-model-item label="姓名" prop="person_name">
          <a-input v-model="editForm.person_name" placeholder="请输入姓名" />
        </a-form-model-item>
        <a-form-model-item label="职位" prop="position">
          <a-input v-model="editForm.position" placeholder="请输入职位" />
        </a-form-model-item>
        <a-form-model-item label="部门" prop="department_id">
          <a-select v-model="editForm.department_id" placeholder="请选择部门">
            <a-select-option v-for="item in departmentList" :key="item.department_id" :value="item.department_id">
              {{ item.department_name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="手机号" prop="phone_number">
          <a-input v-model="editForm.phone_number" placeholder="请输入手机号" />
        </a-form-model-item>
        <a-form-model-item label="系统管理-角色" prop="role_main">
          <a-select v-model="editForm.role_main" placeholder="请选择角色">
            <a-select-option value="普通用户">普通用户</a-select-option>
            <a-select-option value="系统管理员">系统管理员</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="短视频管理-角色" prop="role">
          <a-select v-model="editForm.role" placeholder="请选择角色">
            <a-select-option value="普通用户">普通用户</a-select-option>
            <a-select-option value="审核员">审核员</a-select-option>
            <a-select-option value="系统管理员">系统管理员</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="人员去向-角色" prop="role_destination">
          <a-select v-model="editForm.role_destination" placeholder="请选择角色">
            <a-select-option value="普通用户">普通用户</a-select-option>
            <a-select-option value="部门负责人">部门负责人</a-select-option>
            <a-select-option value="系统管理员">系统管理员</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="公车管理-角色" prop="role_ov">
          <a-select v-model="editForm.role_ov" placeholder="请选择角色">
            <a-select-option value="普通用户">普通用户</a-select-option>
            <a-select-option value="部门负责人">部门负责人</a-select-option>
            <a-select-option value="系统管理员">系统管理员</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
  import moment from 'moment'
  import {
    apiPersonList,
    apiPersonDelete,
    apiPersonUpdate,
    apiPersonUpdateActived,
    apiPersonResetPassword,
    apiPersonCreate,
    apiDepartmentList
  } from '@/api/featch'
  import {
    Base64
  } from '@/assets/js/base64'

  export default {
    name: 'PersonMgr',
    data() {
      // 手机号验证规则
      const validatePhone = (rule, value, callback) => {
        if (value && !/^1[3-9]\d{9}$/.test(value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      }

      return {
        // 表格数据
        tableData: [],
        tableLoading: false,
        loading: false,

        // 部门列表
        departmentList: [],

        // 搜索表单
        searchForm: {
          person_name: '',
          department_id: undefined,
          page: 1,
          page_size: 10
        },

        // 分页信息
        pagination: {
          total: 0,
          page: 1,
          page_size: 10,
          total_pages: 0
        },

        // 新增表单
        createVisible: false,
        createForm: {
          position: '',
          person_name: '',
          department_id: undefined,
          password: '',
          phone_number: '',
          role_main: '普通用户',
          role: '普通用户',
          role_destination: '普通用户',
          role_ov: '普通用户',
        },

        // 表单验证规则
        rules: {
          person_name: [{
              required: true,
              message: '请输入姓名',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 20,
              message: '长度在 2 到 20 个字符',
              trigger: 'blur'
            }
          ],
          department_id: [{
            required: true,
            message: '请选择部门',
            trigger: 'change'
          }],
          // password: [{
          //     required: true,
          //     message: '请输入密码',
          //     trigger: 'blur'
          //   },
          //   {
          //     min: 6,
          //     max: 20,
          //     message: '长度在 6 到 20 个字符',
          //     trigger: 'blur'
          //   }
          // ],
          phone_number: [{
            required: true,
            validator: validatePhone,
            trigger: 'blur'
          }],
          role_main: [{
            required: true,
            message: '请选择角色',
            trigger: 'change'
          }],
          role: [{
            required: true,
            message: '请选择角色',
            trigger: 'change'
          }],
          role_destination: [{
            required: true,
            message: '请选择角色',
            trigger: 'change'
          }],
          role_ov: [{
            required: true,
            message: '请选择角色',
            trigger: 'change'
          }]
        },

        // 编辑表单
        editVisible: false,
        editForm: {
          person_id: undefined,
          person_name: '',
          department_id: undefined,
          password: '',
          phone_number: '',
          role_main: '普通用户',
          role: '普通用户',
          role_destination: '普通用户',
          role_ov: '普通用户',
        },

        // 编辑表单验证规则
        editRules: {
          person_name: [{
              required: true,
              message: '请输入姓名',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 20,
              message: '长度在 2 到 20 个字符',
              trigger: 'blur'
            }
          ],
          phone_number: [{
            validator: validatePhone,
            trigger: 'blur'
          }]
        },
      }
    },
    mounted() {
      // 获取部门列表
      this.getDepartmentList()
      // 获取人员列表
      this.handleGetTableData()
    },
    methods: {
      /**
       * @description 获取部门列表
       */
      getDepartmentList() {
        apiDepartmentList()
          .then(res => {
            if (res.code === 200) {
              this.departmentList = res.data
            }
          })
      },
      /**
       * @description 获取表格数据
       */
      handleGetTableData() {
        this.tableLoading = true
        apiPersonList(this.searchForm)
          .then(res => {
            this.tableLoading = false
            if (res.code === 200) {
              res.data.list.map(item => {
                item.is_actived = (item.is_actived === 1)
              })
              this.tableData = res.data.list
              this.pagination = res.data.pagination
            } else {
              this.$message.error(res.message)
            }
          })
          .catch(err => {
            this.tableLoading = false
            this.$message.error(err.toString())
          })
      },
      /**
       * @description 打开编辑弹窗
       */
      handleEdit(row) {
        this.editVisible = true
        this.editForm = {
          person_id: row.person_id,
          person_name: row.person_name,
          department_id: row.department_id,
          phone_number: row.phone_number,
          role: row.role,
          role_main: row.role_main,
          position: row.position,
          role_destination: row.role_destination,
          role_ov: row.role_ov,
        }
      },
      /**
       * @description 提交编辑
       */
      handleOnEdit() {
        this.$refs.editForm.validate(valid => {
          if (valid) {
            this.loading = true
            // 创建新的对象，避免修改原表单数据
            const submitData = {
              ...this.editForm
            }
            // 如果密码不为空，进行 base64 加密
            if (submitData.password) {
              submitData.password = Base64.encode(submitData.password)
            } else {
              delete submitData.password
            }

            apiPersonUpdate(submitData)
              .then(res => {
                this.loading = false
                if (res.code === 200) {
                  this.$message.success('更新成功')
                  this.editVisible = false
                  this.handleGetTableData()
                  // 重置表单
                  this.$refs.editForm.resetFields()
                } else {
                  this.$message.error(res.message)
                }
              })
              .catch(err => {
                this.loading = false
                this.$message.error(err.toString())
              })
          }
        })
      },
      /**
       * @description 取消编辑
       */
      handleOnEditCancel() {
        this.editVisible = false
        this.$refs.editForm.resetFields()
      },
      /**
       * @description 启用
       */
      handleUpdateActived(row) {
        console.log(row)
        row.is_actived = !row.is_actived
        apiPersonUpdateActived({
          person_id: row.person_id,
          is_actived: row.is_actived ? 1 : 0
        })
      },
      /**
       * @description 重置密码
       */
      handleResetPassword(row) {
        this.tableLoading = true
        apiPersonResetPassword({
            person_id: row.person_id
          })
          .then(res => {
            if (res.code === 200) {
              this.$message.success('密码重置成功')
              this.handleGetTableData()
            } else {
              this.$message.error(res.message)
            }
          })
          .catch(err => {
            this.$message.error(err.toString())
          })
          .finally(() => {
            this.tableLoading = false
          })
      },
      /**
       * @description 删除人员
       */
      handleDelete(row) {
        this.tableLoading = true
        apiPersonDelete({
            person_id: row.person_id
          })
          .then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功')
              this.handleGetTableData()
            } else {
              this.$message.error(res.message)
            }
          })
          .catch(err => {
            this.$message.error(err.toString())
          })
          .finally(() => {
            this.tableLoading = false
          })
      },
      /**
       * @description 打开新增弹窗
       */
      handleCreate() {
        this.createVisible = true
        // 重置表单
        this.$nextTick(() => {
          this.$refs.createForm && this.$refs.createForm.resetFields()
        })
      },
      /**
       * @description 提交新增
       */
      handleOnCreate() {
        this.$refs.createForm.validate(valid => {
          if (valid) {
            this.loading = true
            // 创建新的对象，避免修改原表单数据
            const submitData = {
              ...this.createForm
            }
            // 对密码进行 base64 加密
            submitData.password = Base64.encode(submitData.password)

            apiPersonCreate(submitData)
              .then(res => {
                this.loading = false
                if (res.code === 200) {
                  this.$message.success('新增成功')
                  this.createVisible = false
                  this.handleGetTableData()
                  // 重置表单
                  this.$refs.createForm.resetFields()
                } else {
                  this.$message.error(res.message)
                }
              })
              .catch(err => {
                this.loading = false
                this.$message.error(err.toString())
              })
          }
        })
      },
      /**
       * @description 取消新增
       */
      handleOnCreateCancel() {
        this.createVisible = false
        this.$refs.createForm.resetFields()
      },
      /**
       * @description 搜索
       */
      handleSearch() {
        this.searchForm.page = 1
        this.handleGetTableData()
      },
      /**
       * @description 重置搜索
       */
      handleReset() {
        this.searchForm = {
          person_name: '',
          department_id: undefined,
          page: 1,
          page_size: 10
        }
        this.handleGetTableData()
      },
      /**
       * @description 页码改变
       */
      handlePageChange(page) {
        this.searchForm.page = page
        this.handleGetTableData()
      },
      /**
       * @description 每页条数改变
       */
      handleSizeChange(current, size) {
        this.searchForm.page = 1
        this.searchForm.page_size = size
        this.handleGetTableData()
      }
    }
  }
</script>

<style lang="less" scoped>
  .flex-container {
    display: flex;
    height: 100%;
    width: 100%;

    .right-table-container {
      flex: 1;
      padding: 24px;
      background: #fff;

      .search-form {
        margin-bottom: 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .search-form-left {
          flex: 1;
        }

        .search-form-right {
          margin-left: 16px;
        }
      }

      .table-container {
        position: relative;
      }

      .pagination-container {
        margin-top: 16px;
        text-align: right;
      }
    }
  }
</style>